package cn.mabach.modules.order.controller;

import cn.mabach.modules.sys.entity.SysUserEntity;
import cn.mabach.modules.sys.entity.SysUserTokenEntity;
import cn.mabach.modules.sys.service.ShiroService;

import cn.mabach.order.dto.OrderDeliveryParam;
import cn.mabach.order.dto.OrderDetail;
import cn.mabach.order.entity.OrderEntity;
import cn.mabach.order.entity.OrderOperateHistoryEntity;
import cn.mabach.order.service.OrderOperateHistoryService;
import cn.mabach.order.service.OrderService;
import cn.mabach.order.vo.MoneyInfoParam;
import cn.mabach.order.vo.ReceiverInfoParam;


import cn.mabach.result.PageResult;
import cn.mabach.result.RS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 订单表
 *
 * @author chenshun
 * @email 176468159@qq.com
 * @date 2020-01-02 23:46:11
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShiroService shiroService;
    @Autowired
    private OrderOperateHistoryService historyServiceFeign;



    /**
        * 分页列表
        */
    @GetMapping(value = "/list")
    public PageResult<OrderEntity> getList(@RequestParam(value = "orderSn",required = false) String orderSn,
                                           @RequestParam(value = "receiverKeyword",required = false) String receiverKeyword,
                                           @RequestParam(value = "status",required = false) Integer status,
                                           @RequestParam(value = "orderType",required = false) Integer orderType,
                                           @RequestParam(value = "sourceType",required = false) Integer sourceType,
                                           @RequestParam(value = "createTime",required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date createTime,
                                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {


        RS<PageResult<OrderEntity>> pageResultRS = orderService.queryPage(orderSn,receiverKeyword,status,orderType,sourceType,
                createTime,pageNum,pageSize);

        return pageResultRS.getData();
    }



    /**
     * 根据ID获取信息
     */

    @GetMapping(value = "/{id}")
    public OrderDetail getItem(@PathVariable("id") Long id) {
        return orderService.getByIdE(id).getData();
    }





    /**
     * 根据id保存
     */
    @PostMapping(value = "/create")
    public RS create(@RequestBody OrderEntity orderEntity) {

        RS rs = orderService.saveE(orderEntity);

        return rs;
    }



    /**
     * 根据id修改
     */
    @PostMapping(value = "/update/{id}")
    public RS update(@PathVariable("id") Long id,
                     @Validated @RequestBody OrderEntity entity,
                     BindingResult result) {
        entity.setId(id);
        RS rs = orderService.updateByIdE(entity);

        return rs;
    }

    /**
       * 根据id集合删除
       */
    @PostMapping(value = "/delete")
    public RS deleteBatch(@RequestParam("ids") List<Long> ids) {
        RS rs = orderService.removeByIdsE(ids);
        return rs;
    }

    /**
         * 根据id删除
         */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RS removeByIdE(@PathVariable Long id) {

        return orderService.removeByIdE(id);

    }

    /**
     * 批量发货
     */
    @Transactional
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    public RS delivery(@RequestBody List<OrderDeliveryParam> deliveryParamList ,HttpServletRequest request) {
//        发货
        for (OrderDeliveryParam param : deliveryParamList) {
            RS rs = orderService.delivery(param);
            if (rs.getCode()!=200){
                return RS.error();
            }
//            插入发货日志
            OrderOperateHistoryEntity historyEntity = new OrderOperateHistoryEntity();
            historyEntity.setOrderId(param.getOrderId());
            historyEntity.setCreateTime(new Date());
            historyEntity.setOrderStatus(2);
            historyEntity.setNote("发货成功");
            String token = request.getHeader("token");
            SysUserTokenEntity sysUserTokenEntity = shiroService.queryByToken(token);
            SysUserEntity sysUserEntity = shiroService.queryUser(sysUserTokenEntity.getUserId());
            historyEntity.setOperateMan(sysUserEntity.getUsername());
            historyServiceFeign.saveE(historyEntity);
        }
        return RS.ok();
    }

    /*
    * 批量关闭订单
    * */
    @Transactional
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    public RS close(@RequestParam("ids") List<Long> ids, @RequestParam String note ,HttpServletRequest request) {
//        批量关闭订单
        for (Long id : ids) {
            RS rs = orderService.close(id);
            if (rs.getCode()!=200){
                return RS.error();
            }
//            插入操作日志
            OrderOperateHistoryEntity historyEntity = new OrderOperateHistoryEntity();
            historyEntity.setOrderId(id);
            historyEntity.setOrderStatus(4);
            historyEntity.setCreateTime(new Date());
//获取管理员名
            String token = request.getHeader("token");
            SysUserTokenEntity sysUserTokenEntity = shiroService.queryByToken(token);
            SysUserEntity sysUserEntity = shiroService.queryUser(sysUserTokenEntity.getUserId());
            historyEntity.setOperateMan(sysUserEntity.getUsername());
            historyServiceFeign.saveE(historyEntity);
        }
        return RS.ok();
    }

    /*
    * 修改收货人信息
    * */
    @Transactional
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    public RS updateReceiverInfo(@RequestBody ReceiverInfoParam receiverInfoParam,HttpServletRequest request) {
//        修改收货人信息
        RS rs = orderService.updateReceiverInfo(receiverInfoParam);
        if (rs.getCode()!=200){
            return RS.error();
        }

        //            插入操作日志
        OrderOperateHistoryEntity historyEntity = new OrderOperateHistoryEntity();
        historyEntity.setOrderId(receiverInfoParam.getOrderId());
        historyEntity.setCreateTime(new Date());
        historyEntity.setNote("修改收货人信息");
        historyEntity.setOrderStatus(receiverInfoParam.getStatus());
//获取管理员名

        String token = request.getHeader("token");
        SysUserTokenEntity sysUserTokenEntity = shiroService.queryByToken(token);
        SysUserEntity sysUserEntity = shiroService.queryUser(sysUserTokenEntity.getUserId());
        historyEntity.setOperateMan(sysUserEntity.getUsername());
        historyServiceFeign.saveE(historyEntity);
        return RS.ok();
    }

/*
* 修改订单费用信息
* */

    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @Transactional
    public RS updateReceiverInfo(@RequestBody MoneyInfoParam moneyInfoParam,HttpServletRequest request) {
        RS rs = orderService.updateMoneyInfo(moneyInfoParam);
        if (rs.getCode()!=200){
            return RS.error();
        }
        OrderOperateHistoryEntity history = new OrderOperateHistoryEntity();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());

        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        String token = request.getHeader("token");
        SysUserTokenEntity sysUserTokenEntity = shiroService.queryByToken(token);
        SysUserEntity sysUserEntity = shiroService.queryUser(sysUserTokenEntity.getUserId());
        history.setOperateMan(sysUserEntity.getUsername());
        historyServiceFeign.saveE(history);
        return RS.ok();
    }

    /*
    * 备注订单
    * */
    @Transactional
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    public RS updateNote(@RequestParam("id") Long id,
                                   @RequestParam("note") String note,
                                   @RequestParam("status") Integer status,HttpServletRequest request) {
        RS rs = orderService.updateNote(id, note);
        if (rs.getCode()!=200){
            return RS.error();
        }
        OrderOperateHistoryEntity history = new OrderOperateHistoryEntity();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        String token = request.getHeader("token");
        SysUserTokenEntity sysUserTokenEntity = shiroService.queryByToken(token);
        SysUserEntity sysUserEntity = shiroService.queryUser(sysUserTokenEntity.getUserId());
        history.setOperateMan(sysUserEntity.getUsername());
        history.setOrderStatus(status);
        history.setNote("修改备注信息："+note);
        RS rs1 = historyServiceFeign.saveE(history);
        if (rs1.getCode()!=200){
            return RS.error();
        }
        return RS.ok();
    }

}
